// Copyright (c) 2025, yuxinyong and contributors
// For license information, please see license.txt
// Define a namespace for shared utilities
frappe.shoe_style_utils = frappe.shoe_style_utils || {};

// Define loadAnnotations in the shared namespace
frappe.shoe_style_utils.loadAnnotations = function(frm, rowIdx = null) {
    const overlay = frm.fields_dict.shoe_pic_opt.$wrapper.find('.image-overlay');
    if (!overlay.length) return;
    // 检查是否是新单据且没有子表数据
    if (frm.is_new() && (!frm.doc.shoe_parts || frm.doc.shoe_parts.length === 0)) {
        overlay.find('.annotation-text').remove();
        return;
    }

    const rows = (rowIdx === null) ? (frm.doc.shoe_parts || []) : [frm.doc.shoe_parts[rowIdx - 1]];

    if (rowIdx !== null) {
        const row = rows[0];
        if (row) {
            overlay.find(`.annotation-text[data-idx="${row.idx}"]`).remove();
        }
    } else {
        overlay.find('.annotation-text').remove();
    }

    const annotationFontSize = '12px';

    rows.forEach(row => {
        if (!row) return;
        const position = (row.pic_position || '').trim();
        if (!position) return;

        const parts = position.split(',').map(p => p.trim().replace('%', ''));
        if (parts.length !== 2) return;

        const x = parseFloat(parts[0]);
        const y = parseFloat(parts[1]);
        if (isNaN(x) || isNaN(y)) return;

        const label = row.pic_label || '';
        if (!label) return;

        const color = row.pic_color || 'white';

        const annotText = $('<div class="annotation-text">').css({
            position: 'absolute',
            left: `${x}%`,
            top: `${y}%`,
            color: color,
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
            padding: '2px 5px',
            fontSize: annotationFontSize,
            borderRadius: '3px',
            transform: 'translate(-50%, -50%)',
            zIndex: 15
        }).text(label).attr('data-idx', row.idx);

        overlay.append(annotText);
    });
};

frappe.ui.form.on("Shoe Style", {
    copy_field_to_quick_entry(frm){
	    let article_field = frm.get_docfield("shoe_parts", "article");
		article_field.get_route_options_for_new_doc = function(row) {		
            return {"item_group": "ARTICLE"}        
		}        
        let construction_field = frm.get_docfield("construction");
		construction_field.get_route_options_for_new_doc = function(row) {		
            return {
                "last": row.doc.last
            }        
		}
    },
    setup(frm) {
        frm.trigger("copy_field_to_quick_entry");
    },
    onload(frm){
        if (!frm.doc.drawing_file) {
            frm.get_field("preview_html").$wrapper.html('');
        }
        frappe.shoe_style_utils.loadAnnotations(frm);
    },
	refresh(frm) {
        // 等待仪表板渲染完成
        setTimeout(() => {
            // 隐藏物料相关的加号按钮
            const itemLinks = document.querySelectorAll('.document-link[data-doctype="Item"] .btn-new');
            itemLinks.forEach(btn => {
                btn.style.display = 'none';
            });
        }, 500);

        //console.log('Form refresh triggered for Shoe Style');
        // Wait for the image to render
        setTimeout(() => {
            //console.log('Attempting to find image in shoe_pic_opt');
            // More robust image selector
            const imgWrapper = frm.fields_dict.shoe_pic_opt.$wrapper;
            const img = imgWrapper.find('img[data-name], img:not([src=""])').first();
            if (!img.length) {
                //console.log('No image found in shoe_pic_opt');
                // frappe.show_alert({
                //     message: __('No valid image found in shoe_pic_opt field'),
                //     indicator: 'orange'
                // }, 5);
                return;
            }
            //console.log('Image found:', img.attr('src'));
            img.css('cursor', 'crosshair');
            // Create or get overlay container
            let overlay = imgWrapper.find('.image-overlay');
            if (!overlay.length) {
                overlay = $('<div class="image-overlay">').css({
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: '100%',
                    height: '100%',
                    pointerEvents: 'none', // Allow clicks to pass through to the image
                    zIndex: 10
                });
                imgWrapper.css('position', 'relative'); // Ensure wrapper is positioned
                imgWrapper.append(overlay);
            }
            // Add frame (border) around the image
            img.css({
                border: '2px solid #000', // Customize frame style
                boxSizing: 'border-box'
            });
            img.off('click').on('click', function(event) {
                //console.log('Image clicked', event);
                try {
                    // Get image dimensions and click coordinates
                    const rect = event.target.getBoundingClientRect();
                    const x = event.pageX - rect.left - window.scrollX;
                    const y = event.pageY - rect.top - window.scrollY;
                    const imgWidth = rect.width;
                    const imgHeight = rect.height;
                    if (imgWidth === 0 || imgHeight === 0) {
                        throw new Error('Image has invalid dimensions');
                    }
                    // Calculate percentages
                    const xPercent = ((x / imgWidth) * 100).toFixed(2);
                    const yPercent = ((y / imgHeight) * 100).toFixed(2);
                    const clampedXPercent = Math.max(0, Math.min(100, xPercent));
                    const clampedYPercent = Math.max(0, Math.min(100, yPercent));
                    const coords = clampedXPercent + '%, ' + clampedYPercent + '%';
                    //console.log('Coordinates calculated:', coords);
                    // Clear previous markers and coordinate text
                    const removedMarkers = overlay.find('.marker').remove();
                    const removedText = overlay.find('.coord-text').remove();
                    //console.log('Cleared ' + removedMarkers.length + ' markers and ' + removedText.length + ' text elements');
                    // Add marker at click position
                    const marker = $('<div class="marker">').css({
                        position: 'absolute',
                        left: clampedXPercent + '%',
                        top: clampedYPercent + '%',
                        width: '10px',
                        height: '10px',
                        backgroundColor: 'red',
                        borderRadius: '50%',
                        transform: 'translate(-50%, -50%)', // Center the marker
                        zIndex: 15
                    });
                    overlay.append(marker);
                    // Add text (coordinates) near the marker
                    const coordText = $('<div class="coord-text">').css({
                        position: 'absolute',
                        left: clampedXPercent + '%',
                        top: (clampedYPercent + 2) + '%', // Offset below marker
                        color: 'white',
                        backgroundColor: 'rgba(0, 0, 0, 0.7)',
                        padding: '2px 5px',
                        fontSize: '12px',
                        borderRadius: '3px',
                        transform: 'translate(-50%, 0)',
                        zIndex: 15
                    }).text(coords);
                    overlay.append(coordText);

                    // Remove marker and coordinate text after 5 seconds
                    setTimeout(() => {
                        marker.remove();
                        coordText.remove();
                        //console.log('Removed temporary marker and coordinate text after 5 seconds');
                    }, 5000);

                    // Copy coordinates to clipboard
                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(coords).then(() => {
                            frappe.show_alert({
                                message: __('Coordinates copied: ') + coords,
                                indicator: 'green'
                            }, 3);
                            //console.log('Coordinates copied to clipboard');
                        }).catch(err => {
                            console.error('Clipboard API error:', err);
                            // Fallback: Create a temporary textarea for copying
                            const textarea = document.createElement('textarea');
                            textarea.value = coords;
                            document.body.appendChild(textarea);
                            textarea.select();
                            try {
                                document.execCommand('copy');
                                frappe.show_alert({
                                    message: __('Coordinates copied: ') + coords,
                                    indicator: 'green'
                                }, 3);
                                //console.log('Coordinates copied via fallback');
                            } catch (fallbackErr) {
                                frappe.show_alert({
                                    message: __('Failed to copy coordinates: ') + fallbackErr,
                                    indicator: 'red'
                                }, 5);
                                console.error('Fallback copy error:', fallbackErr);
                            }
                            document.body.removeChild(textarea);
                        });
                    } else {
                        // Fallback for older browsers
                        const textarea = document.createElement('textarea');
                        textarea.value = coords;
                        document.body.appendChild(textarea);
                        textarea.select();
                        try {
                            document.execCommand('copy');
                            frappe.show_alert({
                                message: __('Coordinates copied: ') + coords,
                                indicator: 'green'
                            }, 3);
                            //console.log('Coordinates copied via fallback (no Clipboard API)');
                        } catch (err) {
                            frappe.show_alert({
                                message: __('Failed to copy coordinates: ') + err,
                                indicator: 'red'
                            }, 5);
                            console.error('Fallback copy error:', err);
                        }
                        document.body.removeChild(textarea);
                    }
                } catch (err) {
                    frappe.show_alert({
                        message: __('Error processing click: ') + err.message,
                        indicator: 'red'
                    }, 5);
                    console.error('Click handler error:', err);
                }
            });

            // Load annotations on form refresh
            frappe.shoe_style_utils.loadAnnotations(frm);

        }, 1000);

        frm.trigger("copy_field_to_quick_entry");
        frappe.configure_columns.handle_switch_grid_layout_buttons(frm, "shoe_parts");
        // if (frm.doc.drawing_file) {
        //     frm.set_df_property("preview_html", "hidden", 0);
		// 	zelin_shoe_biz.utils.preview_file(frm);
        // } else {
        //     frm.get_field("preview_html").$wrapper.html('');
        // }
        frm.set_query("article", "shoe_parts", function (doc, cdt, cdn) {
			const row = locals[cdt][cdn];
			return {
				query: "zelin_shoe_biz.queries.get_article",
				filters: {
					shoe_part: row.shoe_part,                    
				},
			};
		});        
        frm.set_query("item_code", "shoe_parts", function(doc, cdt, cdn) {
			const row = locals[cdt][cdn];
            let filters = {shoe_part: row.shoe_part}
            if (row.article){
                filters.article = row.article
            }
			return {
				query: "zelin_shoe_biz.queries.get_item_code",
				filters: filters
			};
        })
        if (frm.doc.grid_layout) {
            frappe.configure_columns.update_grid_columns(frm);
        }
	},

    upload_image: function(frm) {
        let file_picker = new frappe.ui.FileUploader({
            doctype: frm.doc.doctype,
            docname: frm.doc.name,
            allow_multiple: false,
            accept: ['image/*'],
            is_private: true,
            optimize: false,
            dialog: {
                setup: function(dialog) {
                    dialog.fields_dict.is_private.$wrapper.hide();
                    dialog.fields_dict.optimize.$wrapper.hide();
                }
            },
            on_success: function(file) {
                frappe.call({
                    method: 'zelin_shoe_biz.utils.optimize_image',
                    args: {
                        docname: frm.doc.name,
                        file_url: file.file_url
                    },
                    callback: function(r) {
                        if (r.message) {
                            frm.reload_doc();
                            //frappe.msgprint(r.message);
                        }
                    }
                });
            }
        });
    },

	last: function(frm){
		frm.trigger('populate_shoe_parts');
	},

	populate_shoe_parts: function(frm){
        if (frm.doc.shoe_parts && frm.doc.shoe_parts.length === 0){
            frappe
            .call({
                method: "frappe.client.get_list",
                args: {
                    doctype: "Shoe Part",
                    filters:{'is_standard_part': 1},
                    fields: ["name as shoe_part", "shoe_part_ch", "component_type", "item_group", "sorting_sequence"],
                    limit_page_length: 100,
                    order_by: "sorting_sequence",
                },
            })
            .then((r) => {
                if (r.message) {
                    const table_fieldname = 'shoe_parts'
                    frm.clear_table(table_fieldname);
                    r.message.forEach(function(element) {
                        let row = frm.add_child(table_fieldname, element);
                    });
                    frm.refresh_field(table_fieldname);
                }
            });
        }
	},

    construction: function(frm) {
        if (frm.doc.construction) {
            populate_shoe_parts(frm, "CONSTRUCTION", frm.doc.construction);
        } else {
            clear_shoe_parts_by_component_type(frm, "CONSTRUCTION", true);
        }
    },
    grid_layout: function(frm) {
        // This function will be called whenever the `grid_layout` link field changes.
        if (frm.doc.grid_layout) {
            frappe.configure_columns.update_grid_columns(frm);
        }
    }
});

async function populate_shoe_parts(frm, component_type, selected_shoe_component_name) {
    // First, clear existing rows that match the component_type to avoid duplicates
    clear_shoe_parts_by_component_type(frm, component_type, false);

    frm.call({
        method: "zelin_shoe_biz.shoe_biz.doctype.shoe_style.shoe_style.get_shoe_component_shoe_parts",
        args:{
            shoe_component: selected_shoe_component_name
        },
        callback: function(r) {
            if(r.message) {
                const table_fieldname = 'shoe_parts'
                r.message.forEach(function(element) {
                    let row = frm.add_child(table_fieldname, element);
                });
                frm.refresh_field(table_fieldname);
            }
        }
    });
}

function clear_shoe_parts_by_component_type(frm, component_type_to_clear, to_refresh_field) {
    let rows_to_keep = [];
    frm.doc.shoe_parts.forEach(function(row) {
        if (row.component_type !== component_type_to_clear) {
            rows_to_keep.push(row);
        }
    });
    frm.doc.shoe_parts = rows_to_keep;
    to_refresh_field && frm.refresh_field("shoe_parts");
}

function set_update_flag(frm) {
    // This tells the server script to regenerate the image on save
    frm.set_value('annotations_updated', 1);
}
// Child table event handlers for updating annotations on row changes
frappe.ui.form.on('Shoe Part Detail', {
    pic_position: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        frappe.shoe_style_utils.loadAnnotations(frm, row.idx);
        set_update_flag(frm); // <-- Add this line
    },
    pic_label: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        frappe.shoe_style_utils.loadAnnotations(frm, row.idx);
        set_update_flag(frm); // <-- Add this line
    },
    pic_color: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        frappe.shoe_style_utils.loadAnnotations(frm, row.idx);
        set_update_flag(frm); // <-- Add this line
    },
    shoe_parts_add: function(frm, cdt, cdn) {
        // Also trigger on new row addition
        set_update_flag(frm);
    },
    shoe_parts_remove: function(frm, cdt, cdn) {
        frappe.shoe_style_utils.loadAnnotations(frm);
        set_update_flag(frm); // <-- Add this line
    },
    shoe_part: function(frm, cdt, cdn) {
        let child_table = frm.doc.shoe_parts;
        child_table.sort((a, b) => a.sorting_sequence - b.sorting_sequence);
        frm.refresh_field('shoe_parts');
    }
});